
import React, { Component } from 'react';
import {
    View,
    StyleSheet,
    Modal,
    ActivityIndicator,
    Dimensions,
    PermissionsAndroid,
    TouchableOpacity,
    ToastAndroid
} from 'react-native';
import ImageViewer from 'react-native-image-zoom-viewer';
import CameraRoll from "@react-native-community/cameraroll";
import RNFS from 'react-native-fs';
const { width, height } = Dimensions.get('window');
const Width = () => { return width };
const Height = () => { return height };






/** 放大图片弹窗组件 */
class ZoomPictureModel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isShowImage: this.props.isShowImage,
            loadingAnimating: true,
            zoomImages: this.props.zoomImages,
            currShowImgIndex: this.props.currShowImgIndex,
            androidDownPath : `${RNFS.DocumentDirectoryPath}/${((Math.random() * 1000) | 0)}.jpg`
        }
    }

    componentWillReceiveProps(nextProps) {
        if (this.state.isShowImage != nextProps.isShowImage) {
            this.setState({
                isShowImage: nextProps.isShowImage
            })
        }
        if (this.state.zoomImages != nextProps.zoomImages) {
            this.setState({
                zoomImages: nextProps.zoomImages
            })
        }
        if (this.state.currShowImgIndex != nextProps.currShowImgIndex) {
            this.setState({
                currShowImgIndex: nextProps.currShowImgIndex
            })
        }
    }

    handleZoomPicture(flag) {
        this.setState({
            isShowImage: flag
        })
        this.props.callBack(flag)
    }


    async requestReadPermission() {
        try {
            //返回string类型
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限 
                    'title': '我要读写权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.show("你已获取了读写权限")
            } else {
                this.show("获取读写权限失败")
            }
        } catch (err) {
            this.show(err.toString())
        }
    }
    

    //获取用户存储权限的
    async requestReadPermission() {
        try {
            //返回string类型
            const granted = await PermissionsAndroid.request(
                PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                {
                    //第一次请求拒绝后提示用户你为什么要这个权限
                    'title': '我要读写权限',
                    'message': '没权限我不能工作，同意就好了'
                }
            )
            if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                this.show("你已获取了读写权限")
            } else {
                this.show("获取读写权限失败")
            }
        } catch (err) {
            this.show(err.toString())
        }
    }
    //弹窗
    show(data) {
        ToastAndroid.show(data,ToastAndroid.SHORT)
    }

    // 保存图片  
    savePhoto() {
        let index = this.props.currShowImgIndex;
        let url = this.props.zoomImages[index].url;

        if (Platform.OS === 'ios') {  //ios图片保存
            let promise = CameraRoll.save(url);
            promise.then(function (result) {
                alert("已保存到系统相册")
            }).catch(function (error) {
                alert('保存失败！\n' + error);
            });
        } else {  //Android  先下载到本地
            let DownloadFileOptions = {
                fromUrl: url,          //下载路径
                toFile: this.state.androidDownPath     // Local filesystem path to save the file to
            }
            let result = RNFS.downloadFile(DownloadFileOptions);
            let _this = this;
            result.promise.then(function (val) {
                console.log("文件保存成功：" + _this.state.androidDownPath)

                //要先获取用户的读写权限
                _this.requestReadPermission()
                let that = _this
                //查询是否获取读写权限
                try {
                    //返回Promise类型
                    const granted = PermissionsAndroid.check(
                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
                    )
                    granted.then((data)=>{
                        // that.show("是否获取读写权限"+data)

                        if(data){
                            let promise = CameraRoll.save(that.state.androidDownPath);
                            promise.then(function (result) {
                                that.show('已保存到相册')
                            }).catch(function (error) {
                                alert('保存失败！\n' + error);
                            });
                        }

                    }).catch((err)=>{
                        that.show(err.toString())
                    })
                } catch (err) {
                    this.show(err.toString())
                }
                
 
            }, 
            function (val) {
                console.log('Error Result:' + JSON.stringify(val));
            }
            ).catch(function (error) {
                console.log('这里有问题了')
                console.log(error.message);
            })
        }
 
    }

    // 图片加载
    renderImageLoad() {
        let { loadingAnimating } = this.state
        return (
            <View style={styles.img_load}>
                <ActivityIndicator animating={loadingAnimating} size={"large"} />
            </View>
        )
    }

    render() {
        let { isShowImage, zoomImages, currShowImgIndex } = this.state
        return (
            <View style={styles.container}>
                <Modal
                    visible={isShowImage}
                    animationType={"slide"}
                    transparent={true}
                    >
                    <ImageViewer style={styles.zoom_pic_img}
                        enableImageZoom={true}
                        saveToLocalByLongPress={true}
                        menuContext={{ "saveToLocal": "保存图片", "cancel": "取消" }}
                        onSave={(url) => { this.savePhoto(url) }}
                        loadingRender={() => this.renderImageLoad()}
                        enableSwipeDown={true}
                        imageUrls={zoomImages}
                        index={currShowImgIndex}
                        onClick={() => this.handleZoomPicture(false)}
                    />
                </Modal>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    zoom_pic_img: {
        maxWidth: Width()
    },
    img_load: {
        marginBottom: (Height() / 2) - 40
    }
})

export default ZoomPictureModel;

